package com.jishuo.base.util;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.List;

/**
 * 
 * Json 工具类
 *
 */
public class GsonUtil {

	/**
	 * json转List
	 * @param json json字符串
	 * @param clazz 实体类型
	 * @return
	 */
	public static <T>List<T> fromJsonToList(String json, Class<T> clazz) {
		Gson gson = new Gson();
		Type listType = TypeToken.getParameterized(List.class, clazz).getType();
		return gson.fromJson(json, listType);
	}

	/**
	 * 对账转json
	 * @param obj 对象
	 * @return
	 */
	public static String fromObjectToJson(Object obj) {
		Gson gson = new Gson();
		return gson.toJson(obj);
	}

	/**
	 * 把java对象转换成JSON对象，并输出到前�?
	 * @author wxf
	 * @param object
	 * @param response
	 * @throws Exception
	 */
	public static void toJsonAndWriteOnJsp(Object object,HttpServletResponse response) throws Exception{
		Gson gson = new Gson();
		String gsonStr = gson.toJson(object);
//		System.out.println(gsonStr);
		response.setContentType("text/json;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.write(gsonStr);
		out.flush();
		out.close();
	}
	/*
	 * @author zj
	 * java对象转为json rows对象
	 *
	 */
	public static void  GetJSONFromDataTable(Object object,Integer recorCount,HttpServletResponse response) throws Exception
	{
		Gson gson = new Gson();
		String gsonStr = gson.toJson(object);
		gsonStr="{\"Rows\":"+gsonStr+",\"Total\":"+recorCount+"}";
		response.setContentType("text/json;charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		out.write(gsonStr);
		out.flush();
		out.close();
	}
	
}
